package com.jfcloud.mall.user.service.impl;

import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jfcloud.common.exception.BussinessException;
import com.jfcloud.common.utils.MD5;
import com.jfcloud.mall.user.domain.JfcloudUser;
import com.jfcloud.mall.user.domain.JfcloudUserToken;
import com.jfcloud.mall.user.domain.dto.GrantParams;
import com.jfcloud.mall.user.persistent.JfcloudUserService;
import com.jfcloud.mall.user.persistent.JfcloudUserTokenService;
import com.jfcloud.mall.user.service.TokenService;

/**
 * 简易token授权模式<br>
 * 认证通过后颁发token,token内容为：指定字段组拼接后的MD5<br>
 * 被授权者后续通过该token调用 信息获取 接口获取所需数据
 * @author zhaojunfu
 *
 */
@Service(value = "SimpleTokenServiceImpl")
@Transactional
public class SimpleTokenServiceImpl implements TokenService {

	private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTokenServiceImpl.class);
	
	@Autowired
	private JfcloudUserService jfcloudUserService;
	@Autowired
	private JfcloudUserTokenService jfcloudUserTokenService;
	
	@Override
	public Object grant(GrantParams params) {
		//1.参数校验
		String username = params.getUsername();
		String password = params.getPassword();
		Assert.notNull(username, "用户名不能为空");
		Assert.notNull(password, "密码不能为空");
		//2.认证
		JfcloudUser user = null;
		try{
			user=jfcloudUserService.getOne(new QueryWrapper<JfcloudUser>().eq("username", username) );
		}catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			throw new BussinessException("账号异常");
		}
		Assert.notNull(user, "账号不存在");
		String dbPwd = user.getPassword();
		if(password.equals(dbPwd)) {
			//验证通过
			//3.判断是否已有token
			JfcloudUserToken oldToken = jfcloudUserTokenService.getOne(
					new QueryWrapper<JfcloudUserToken>().eq("user_id", user.getId())
					.eq("status", 1)
					.eq("is_delete", 0));
			if(oldToken!=null) return oldToken.getToken();
			//4.颁发token
			JfcloudUserToken token = new JfcloudUserToken();
			token.setUserId(user.getId());
			token.setCreateTime(LocalDateTime.now());
			token.setStatus(1);
			//可指定任意数量的字段进行拼接MD5
			String md5Token = MD5.generate(user.getId(),user.getUsername(),user.getPassword(),token.getCreateTime());
			token.setToken(md5Token);
			token.setIsDelete(0);
			jfcloudUserTokenService.save(token);
			return md5Token;
		}else {
			//验证不通过
			throw new BussinessException("密码不正确");
		}
	}
	

	@Override
	public Object validateAndGet(Object token) {
		JfcloudUserToken oldToken = jfcloudUserTokenService.getOne(
				new QueryWrapper<JfcloudUserToken>().eq("token", token)
				.eq("status", 1)
				.eq("is_delete", 0));
		Assert.notNull(oldToken, "token已失效");
		
		JfcloudUser user = jfcloudUserService.getById(oldToken.getUserId());
		
		Assert.isTrue(user.getIsDelete().equals(0), "用户已被删除");
		
		return user;
	}
}
